<template>
<div class="editForm">
  <el-tabs type="border-card">
    <el-tab-pane label="编辑内容">
      <el-form :inline="true" ref="formForm" :rules="rules" :model="formForm" >
        <el-form-item class="block-line">
          <el-col class="cont-left" :span="10" v-show="!edit.choose">
            <el-form-item label="表单名称：" class="block-line" prop="title">
              <el-input v-model="formForm.title" :maxlength="30" placeholder="您可输入30字…"></el-input>
            </el-form-item>
            <el-tabs class="child-tab" v-model="formTab" type="card" @tab-click="tabClick">
              <el-tab-pane label="表单" name="form" key="0"></el-tab-pane>
              <el-tab-pane label="内容" name="content" key="1"></el-tab-pane>
              <el-tab-pane label="样式" name="style" key="2"></el-tab-pane>
            </el-tabs>
            <el-form-item class="block-line" v-show="formTab=='form'">
              <el-form-item label="按钮提交的文字" class="block-line">
                <el-input v-model="formForm.node.buttonText" :disabled="buttonTextEdit" placeholder="提交"></el-input>
              </el-form-item>
              <el-form-item label="表单提交后行为" class="block-line">
                <el-radio-group v-model="formForm.submitBehavior" @change="submitBehaviorChange">
                  <el-radio :label="1">显示文字</el-radio>
                  <el-radio :label="2">跳转到网页</el-radio>
                  <el-radio :label="3">转到微页面</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item class="block-line" v-show="formForm.submitBehavior==1">
                <!-- 加载编辑器的容器 -->
                <form-editor  ref="editor"
                  :content.sync="formForm.showText"
                  @contentChange="handleEditorChange">
                </form-editor>
              </el-form-item>
              <el-form-item class="block-line" v-show="formForm.submitBehavior==2">
                <el-input v-model="formForm.toWebpage" placeholder="http://"></el-input>
              </el-form-item>
              <el-form-item class="block-line" v-if="formForm.submitBehavior==3">
                <el-select class="block-line"
                  ref="select"
                  v-model="formForm.node.wepageTitle"
                  remote
                  filterable
                  placeholder="输入关键词搜索"
                  clearable
                  :filter-method="chooseWepage"
                  @change="handleSelect">
                  <el-option v-for="item,n in pageList.list" :value="item.title" :label="item.title" :key="n.toString()"></el-option>
                </el-select>
                <!-- <el-select class="block-line"
                  v-model="formForm.toWepage"
                  filterable
                  placeholder="输入关键词搜索"
                  remote
                  :remote-method="chooseWepage"
                  @change="handleSelect">
                  <el-option v-for="item,n in pageList.list" :value="item.microPageUrl" :label="item.title" :key="n.toString()"></el-option>
                </el-select> -->
              </el-form-item>
              <el-form-item class="block-line">
                <el-checkbox v-model="formForm.cusBlankLimit">每个客户限填一次</el-checkbox>
              </el-form-item>
              <!-- <el-form-item class="block-line" label="提交后加入群组">
                <el-select class="block-line" placeholder="不加入" clearable v-model="formForm.submitGroup">
                  <el-option key="item" value="index" label="不加入"></el-option>
                  <el-option key="item1" value="index1" label="item1"></el-option>
                  <el-option key="item2" value="index2" label="item2"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item class="block-line" label="提交后提升到阶段">
                <el-select class="block-line" placeholder="不提升" clearable v-model="formForm.submitStage">
                  <el-option key="item" value="index" label="不提升"></el-option>
                  <el-option key="item1" value="index1" label="item1"></el-option>
                  <el-option key="item2" value="index2" label="item2"></el-option>
                </el-select>
              </el-form-item> -->
            </el-form-item>
            <!-- 内容块 -->
            <el-form-item class="block-line form-content" v-show="formTab=='content'">
              <form-cont ref="formcont" :payData="payData" @setPayBtnTxt="setPayBtnTxt"></form-cont>
            </el-form-item>
            <!-- 样式块 -->
            <el-form-item class="block-line form-style cl" v-show="formTab=='style'">
              <form-style :styleObj.async="formForm.node.style"></form-style>
            </el-form-item>
          </el-col>
          <el-col class="cont-left" :span="10" v-show="edit.choose">
            <form-cont-edit :editObj.async="edit" v-on:delItem="delItem" v-on:editSure="editSure"></form-cont-edit>
          </el-col>
          <el-col :span="14" class="cont-right">
            <el-form-item class="form-cont-wrap">
              <fieldset>
                <div class="content-wrap" :style="{
                  fontFamily: formForm.node.style.font.family,
                  fontSize: formForm.node.style.font.size,
                  fontWeight: formForm.node.style.font.weight?'bold':'normal',
                  color: formForm.node.style.font.color
                }">
                  <draggable v-model="formHtmlMap" :move="dragMove">
                    <div v-for="item, index in formHtmlMap" @click="handleItemClick(item, index)"
                      :class="{
                        'cont-item': true,
                        'focus': showMenu===index,
                        'cont-item-m0': formForm.node.style.lineHeight==='小',
                        'cont-item-m5': formForm.node.style.lineHeight==='中',
                        'cont-item-m10': formForm.node.style.lineHeight==='大'
                      }" >
                      <label v-if="item.type!='pay'" class="cont-item-label" for="">{{item.label}} <span v-if="item.required" class="cont-item-required">*</span></label>
                      <!-- <p class="cont-item-desc" v-if="item.desc!=''">{{item.desc}}</p> -->
                      <div v-if="item.type=='text'">
                        <input type="text" :name="item.label" class="cont-item-ipt" :tip="item.name">
                        <div v-if="item.name=='mobile' && item.vcodeShow" class="vcode-wrap">
<!--                           <div>
                            <input type="text" name="图片验证码" class="cont-item-ipt cont-item-ipt-short" id="imgCode" placeholder="请输入图片验证码">
                            <img id="getCaptcha" src="" alt="图片验证码"/>
                          </div> -->
                          <div>
                            <input type="text" name="手机验证码" class="cont-item-ipt cont-item-ipt-short" id="smsCode" placeholder="请输入手机验证码" tip="vCode">
                            <span id="getVcode">获取验证码</span>
                          </div>
                        </div>
                      </div>
                      <input v-else-if="item.type=='date'" type="date" :name="item.label" class="cont-item-ipt">
                      <textarea v-else-if="item.type=='textarea'" :name="item.label" class="cont-item-ipt"></textarea>
                      <div v-else-if="item.type=='select'">
                        <select v-for="key, n in item.options" :name="item.name + n.toString() + index.toString()" class="cont-item-select">
                          <option v-for="k in key" :value="k.val">{{k.label}}</option>
                        </select>
                        <input type="hidden" :name="item.label">
                      </div>
                      <div v-else-if="item.type=='radio'">
                        <p v-for="key in item.options[0]" class="cont-item-radio">
                          <label :for="item.label">
                            <input type="radio" :value="key.label" :name="item.label">
                            {{key.label}}
                          </label>
                        </p>
                      </div>
                      <div v-else-if="item.type=='checkbox'">
                        <p v-for="key in item.options[0]" class="cont-item-checkbox">
                          <label :for="item.label">
                            <input type="checkbox" :value="key.label" :name="item.label">
                            {{key.label}}
                          </label>
                        </p>
                      </div>
                      <div v-else-if="item.type=='file'" class="file-upload">
                        <input class="upload-input" type="file" value="" :name="'upload'+item.label" accept="image/*">
                        <a href="javascript:;" class="upload-btn">选择文件</a>
                        <p class="file-tip">请选择上传的图片，最多5张</p>
                        <ul class="file-list">
                        </ul>
                      </div>
                      <div v-else-if="item.type=='pay'" class="pay-wrap">
                        <button :id="item.name+'_'+item.payBtnInd" class="pay-btn">{{item.label}}</button>
                      </div>

                      <p class="cont-item-pic">
                        <img v-for="k in item.pic" :src="k" alt="">
                      </p>
                      <div class="op">
                        <i class="icon icon-edit" @click="editItem(item, index)"></i>
                        <i class="icon icon-guanbi" v-show="showDelBtn(item)" @click="delItem(index)"></i>
                      </div>
                    </div>
                  </draggable>
                  <div class="btn-wrap" :style="{textAlign: formForm.node.style.layout==1?'left':formForm.node.style.layout==2?'center':'right'}" v-show="formForm.node.buttonText">
                    <button class="form-btn">{{formForm.node.buttonText}}</button>
                  </div>
                </div>
              </fieldset>
            </el-form-item>
          </el-col>
        </el-form-item>
      </el-form>
    </el-tab-pane>
    <!-- <el-tab-pane label="背景图片">
      <form-background :formObj.async="formForm"></form-background>
    </el-tab-pane> -->
    <el-row class="submit-wrap">
      <el-col :span="24">
        <el-button type="primary" style="width:100px" @click="submitFormData('formForm')" :loading="submitSave" :disabled="edit.choose">{{formForm.save?'保存':'返回'}}</el-button>
        <el-button type="primary" style="width:100px" @click="formView()">预览</el-button>
      </el-col>
    </el-row>
  </el-tabs>
  <el-dialog
    title="预览"
    :visible.sync="dialogView"
    width="30%">
    <p>扫二维码在手机上预览</p>
    <img class="view-img" :src="viewFormImg" alt="">
  </el-dialog>
</div>
</template>
<script>
  import {mapState, mapActions, mapMutations} from 'vuex'
  import draggable from 'vuedraggable'
  import formEditor from '@/components/common/content/form/formEditor'
  import formCont from '@/components/common/content/form/formCont'
  import formStyle from '@/components/common/content/form/formStyle'
  import formContEdit from '@/components/common/content/form/formContEdit'
  import formBackground from '@/components/common/content/form/formBackground'
  import css from 'css-loader!@/style/form.wecss'
  import 'vue-style-loader!css-loader!@/style/form.wecss'
  import exec from '@/utils/formCheck'
  export default {
    data () {
      return {
        formTab: 'form',
        submitSave: false,
        viewFormId: '',
        dialogView: false,
        viewFormImg: '',
        buttonTextEdit: false,
        formForm: {
          id: this.$route.params.id === 'add' ? '' : this.$route.params.id,
          title: '',
          content: '',
          save: true,
          node: {
            buttonText: '提交',
            wepageTitle: '',
            style: {
              font: {
                family: '微软雅黑',
                size: '14px',
                weight: false,
                color: '#555555'
              },
              lineHeight: '中',
              layout: 2
            },
            formNode: []
          },
          submitBehavior: 1,
          showText: '',
          toWebpage: '',
          toWepage: '',
          publishStatus: 0,
          cusBlankLimit: false,
          cardId: '',
          cardAppid: '',
          payAppid: ''
          // submitGroup: '',
          // submitStage: ''
        },
        edit: {
          choose: false,
          type: null,
          name: '',
          required: false
        },
        showMenu: null,
        rules: {
          title: {required: true, message: '请输入表单名称', trigger: 'blur'},
          buttonText: {required: true, message: '请输入表单提交按钮的文字', trigger: 'blur'},
          url: /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-.,@?^=%&:/~+#]*[\w\-@?^=%&/~+#])?/
        }
      }
    },
    components: {
      formEditor, draggable, formCont, formStyle, formContEdit, formBackground
    },
    mounted () {
      this.SET_FORM_HTML_MAP([{
        addFieldInd: 0,
        label: '姓名',
        name: 'name',
        required: true,
        type: 'text',
        options: [],
        pic: []
      },
        {
          addFieldInd: 1,
          label: '手机号码',
          name: 'mobile',
          required: true,
          type: 'text',
          options: [],
          pic: []
        }])
      this.$store.state.contentManage.wePageList.list = []
      this.initPage()
      // console.log(this.pageList)
    },
    computed: {
      ...mapState({
        formDetail: state => state.contentManage.formDetail,
        pageList: state => state.contentManage.wePageList,
        payData: state => state.contentManage.payData
      }),
      formHtmlMap: {
        get () {
          return this.$store.state.contentManage.formHtmlMap
        },
        set (value) {
          this.formForm.node.formNode = this.$_.cloneDeep(value)
          this.SET_FORM_HTML_MAP(value)
        }
      }
    },
    methods: {
      ...mapActions(['getFormDetail', 'getWePageList', 'saveForm', 'viewForm']),
      ...mapMutations(['SET_FORM_HTML_MAP', 'SET_PAY_DATA']),
      tabClick () {
        // if (this.formTab === 'content') {
        //   this.$refs.formcont.initFieldList()
        // }
      },
      async initPage () {
        if (this.formForm.id) {
          await this.getFormDetail(this.formForm.id)
          this.formForm = {...this.formDetail}
          this.formForm.id = this.$route.params.id === 'add' ? '' : this.$route.params.id
          this.formForm.cusBlankLimit = Boolean(this.formForm.cusBlankLimit)
          if (this.formForm.submitBehavior !== 3) {
            this.formForm.toWepage = ''
          }
          if (this.formDetail.node) {
            this.formForm.node = JSON.parse(this.formDetail.node)
            if (this.formForm.node.wepageTitle) {
              this.chooseWepage(this.formForm.node.wepageTitle)
            }
            if (this.payData.length > 0) {
              this.formForm.payAppid = this.payData[0].wxPayAcc
              // this.formForm.cardAppid = this.payData[0].ticketType
              // this.formForm.cardId = this.payData[0].cardId
              this.formForm.cardTemplateId = this.payData[0].cardTemplateId
              this.setPayBtnTxt()
            }
          }
        } else {
          this.SET_PAY_DATA([])
        }
        this.$refs.formcont.initFieldList()
      },

      // 是否显示表单项删除按钮
      showDelBtn(item) {
        const items = ['name', 'mobile']
        return items.indexOf(item.name) === -1
      },

      chooseWepage (query) {
        if (query) {
          this.getWePageList({
            title: query,
            publishStatus: 1,
            page: 1,
            size: 100
          })
        }
      },
      handleSelect (value) {
        let obj = {}
        obj = this.pageList.list.find((item) => {
          return item.title === value
        })
        if (obj) {
          this.formForm.toWepage = obj.microPageUrl
        }
      },
      submitBehaviorChange (val) {
        // console.log(this.formForm.submitBehavior)
      },
      // 编辑器内容改变
      handleEditorChange (cont) {
        return cont
      },
      // 可拖拽元素点击
      handleItemClick (item, index) {
        if (this.showMenu === index) {
          this.showMenu = null
        } else {
          this.showMenu = index
        }
      },
      // 元素拖拽时关闭编辑
      dragMove () {
        this.edit.choose = false
      },
      // 编辑表单元素
      editItem (item, index) {
        this.edit = this.$_.cloneDeep(item)
        this.edit.choose = true
        this.edit.index = index
      },
      // 删除表单元素
      delItem (index) {
        this.$refs.formcont.delFieldCont(this.formHtmlMap[index].addFieldInd)
        this.formHtmlMap.map(item => {
          if (item.addFieldInd && item.addFieldInd > this.formHtmlMap[index].addFieldInd) {
            item.addFieldInd--
          }
          if (item.type === 'pay' && item.payBtnInd > this.formHtmlMap[index].payBtnInd) {
            item.payBtnInd--
          }
        })
        if (this.formHtmlMap[index].type === 'pay') {
          this.payData.splice(this.formHtmlMap[index].payBtnInd, 1)
          this.SET_PAY_DATA(this.payData)
          this.formForm.payAppid = ''
          this.formForm.cardAppid = ''
          this.formForm.cardId = ''
          this.formForm.cardTemplateId = ''
        }
        if (this.payData.length === 0) {
          this.buttonTextEdit = false
          this.formForm.node.buttonText = '提交'
        }
        this.formHtmlMap.splice(index, 1)
        this.SET_FORM_HTML_MAP(this.formHtmlMap)
        this.edit.choose = false
        this.showMenu = null
      },
      // 编辑确定
      editSure (obj) {
        console.log(234)
        this.edit = obj
        this.formHtmlMap[obj.index] = {...obj}
        if (obj.type === 'pay') {
          this.payData[obj.payBtnInd] = obj.payObj
          this.SET_PAY_DATA(this.payData)
          if (obj.wxPayAcc === '') {
            this.$message.warning('支付的公众号不能为空！')
            return false
          }
          // if (obj.cardId === '') {
          //   this.$message.warning('支付的卡券不能为空！')
          //   return false
          // }
          if (obj.cardTemplateId === '') {
            this.$message.warning('支付的卡券不能为空！')
            return false
          }
          if (obj.payObj.payVal === '' || obj.payObj.payVal < 0) {
            this.$message.warning('支付金额不能为空和负数！')
            return false
          }
          this.formForm.payAppid = obj.wxPayAcc
          // this.formForm.cardAppid = obj.ticketType
          // this.formForm.cardId = obj.cardId
          this.formForm.cardTemplateId = obj.cardTemplateId
        }
        this.SET_FORM_HTML_MAP(this.formHtmlMap)
        this.showMenu = null
        this.edit.choose = false
      },
      setPayBtnTxt () {
        this.buttonTextEdit = true
        this.formForm.node.buttonText = ''
      },
      // 校验表单数据
      checkForm () {
        let form = this.formForm
        if (form.node.formNode.length === 0) {
          this.$message.warning('表单内容不能为空')
          return false
        }
        if (this.payData.length > 0) {
          let payChk = true
          this.payData.map((item) => {
            if (item.payVal === '' || item.cardTemplateId === '' || item.cardTemplateId === undefined || item.wxPayAcc === '') {
              payChk = false
            }
          })
          if (!payChk) {
            this.$message.warning('请完善支付信息')
            return false
          }
        } else {
          if (form.node.buttonText === '') {
            this.$message.warning('表单按钮提交的文字不能为空')
            return false
          }
          if (form.submitBehavior === 1) {
            this.formForm.showText = this.$refs.editor.getEditorCont()
            if (form.showText === '') {
              this.$message.warning('显示文字不能为空')
              return false
            } else {
              this.formForm.toWebpage = null
              this.formForm.toWepage = null
              this.formForm.node.wepageTitle = ''
            }
          } else if (form.submitBehavior === 2) {
            if (form.toWebpage === '') {
              this.$message.warning('跳转网页地址不能为空')
              return false
            } else if (!this.rules.url.test(form.toWebpage)) {
              this.$message.warning('跳转网页地址格式不对')
              return false
            } else {
              this.formForm.showText = ''
              this.formForm.toWepage = null
              this.formForm.node.wepageTitle = ''
            }
          } else if (form.submitBehavior === 3) {
            if (!form.toWepage) {
              this.$message.warning('请选择要跳转的微页面')
              return false
            } else {
              this.formForm.toWebpage = null
              this.formForm.showText = ''
            }
          }
        }
        return true
      },
      // 保存表单数据
      submitFormData (form) {
        let me = this
        if (!me.formForm.save) {
          me.$router.go(-1)
        } else {
          this.formForm.node.formNode = this.$_.cloneDeep(this.formHtmlMap)
          if (!this.checkForm()) return
          let style = '<style>' + css + '</style>'
          // let tit = '<h3 class="form-title">' + this.formForm.title + '</h3>'
          let op = /<div class="op"><i class="icon icon-edit"><\/i> <i class="icon icon-guanbi"><\/i><\/div>/g
          let cont = document.querySelector('fieldset').innerHTML.replace(op, '')
          let zeptoJs = '<script src="http://apps.bdimg.com/libs/zepto/1.1.4/zepto.min.js"></' + 'script>'
          let areaJs = (cont.indexOf('<select name="area0') > -1 && cont.indexOf('<select name="area1') > -1) ? '<script src="http://orgsd4jq1.bkt.clouddn.com/pca-code.js"></' + 'script>' : '<script type="text/javascript">let areaData = []</' + 'script>'
          let afterSubmit = {
            type: this.formForm.submitBehavior,
            showText: this.formForm.showText,
            toWebpage: this.formForm.toWebpage,
            toWepage: this.formForm.toWepage
          }
          let payDataStr = ''
          if (this.payData.length > 0) {
            this.payData.map(function(elem) {
              payDataStr += JSON.stringify(elem) + 't|c|l'
            })
          }
          let script = '<script type="text/javascript">\nvar afterSubmit=' + JSON.stringify(afterSubmit) + ';\nvar payDataStr=\'' + payDataStr + '\';\n var exec=' + exec.exec + '\nvar run = new exec();\nrun.init()\n</' + 'script>'
          this.formForm.cusBlankLimit = Number(this.formForm.cusBlankLimit)
          this.formForm.content = style + '\n' + cont + '\n' + zeptoJs + '\n' + areaJs + '\n' + script
          this.$refs[form].validate(valid => {
            if (valid) {
              this.submitSave = true
              this.saveForm(this.formForm)
                .then(res => {
                  if (res.data.code === 1) {
                    if (this.$route.params.id === 'add') {
                      me.formForm.id = me.viewFormId = res.data.data.id
                    }
                    this.$message({
                      type: 'success',
                      message: '提交成功'
                    })
                  } else {
                    this.$message({
                      type: 'warning',
                      message: res.data.msgZ
                    })
                  }
                  me.submitSave = false
                  this.formForm.cusBlankLimit = Boolean(this.formForm.cusBlankLimit)
                })
            }
          })
        }
      },
      // 预览
      formView () {
        this.viewFormId = this.$route.params.id === 'add' ? this.viewFormId : this.$route.params.id
        if (!this.viewFormId) {
          this.$message.warning('请先保存保单数据')
        } else {
          this.viewForm(this.viewFormId).then(res => {
            let dat = res.data
            if (dat.code === 1) {
              this.dialogView = true
              this.viewFormImg = 'data:image/png;base64,' + dat.data.QRCode
            }
          })
        }
      }
    }
  }
</script>
<style lang="scss" scope>
  .editForm{
    line-height: 18px;
    max-width: 1200px;
    .el-form{min-width: 1055px;}
    .block-line{display:block;width:100%;}
    .block-line .el-form-item__content{display: block;}
    .child-tab{
      margin-top: 20px;
    }
    .cont-left{min-width: 438px;}
    .cont-right{min-width: 615px;}
    fieldset{border: none;}
  }
  .el-checkbox__label em{
    color: #ccc;
  }
  .submit-wrap{
    padding: 20px 0;
    border-top: 1px solid #ccc;
    text-align: center;
  }
  .form-cont-wrap{
    border: 1px solid rgb(191, 203, 217);
    margin: 20px 30px;
    min-width: 400px;
    padding: 20px 50px;
    .cont-item, .btn-wrap{
      &{position:relative;display:inline-block;width:100%;padding: 0 15px;}
      &:after{
        position: absolute;
        z-index: 98;
        height: 100%;
        width: 100%;
        top: 0px;
        left: 0px;
        content: '';
      }
      &:hover, &.focus{
        outline:1px solid #ccc;
        .op{display:block;}
      }
      .op{display:none;position:absolute;top:0;right:0;padding:0 10px;background:#666;z-index:99}
      .op .icon{margin:0 2px;color:#fff;font-weight:700;cursor:pointer;font-size:12px;&:hover{color:#2eb2ed;}}
    }
  }
  .view-img{
    width: 250px;
    height: 250px;
    display: block;
    margin: 15px auto;
  }
</style>
